package models

import (
	"errors"
	"fmt"
	"reflect"
	"strings"
	"time"

	"github.com/astaxie/beego/orm"
	"gitee.com/lzqysoft/ims/libs/encrypt"
)

type Pay struct {
	Id       string    `orm:"column(id);pk"`
	StockId  string    `orm:"column(yjk_stock_id)"`
	BuyId    string    `orm:"column(buy_id)"`
	Seq      int       `orm:"column(seq)"`
	Money    float64   `orm:"column(money)"`
	Date     time.Time `orm:"column(date);type(date)"`
	Remark   string    `orm:"column(remark);null"`
	Status   int       `orm:"column(status)"`
	Isdelete int       `orm:"column(isdelete)"`
	Ctime    time.Time `orm:"column(ctime);type(timestamp with time zone)"`
	Creater  string    `orm:"column(creater);null"`
	Utime    time.Time `orm:"column(utime);type(timestamp with time zone)"`
	Updater  string    `orm:"column(updater);null"`
}
type PayItem struct {
	Date   time.Time
	Money  float64
	Remark string
	Seq    int
}

func (t *Pay) TableName() string {
	return "yjk_pay"
}

func init() {
	orm.RegisterModel(new(Pay))
}

// AddPay insert a new Pay into database and returns
// last inserted Id on success.
func AddPay(m *Pay) (id int64, err error) {
	o := orm.NewOrm()
	id, err = o.Insert(m)
	return
}

// GetPayById retrieves Pay by Id. Returns error if
// Id doesn't exist
func GetPayById(id string) (v *Pay, err error) {
	o := orm.NewOrm()
	v = &Pay{Id: id}
	if err = o.Read(v); err == nil {
		return v, nil
	}
	return nil, err
}

// GetAllPay retrieves all Pay matches certain condition. Returns empty list if
// no records exist
func GetAllPay(query map[string]string, fields []string, sortby []string, order []string,
	offset int64, limit int64) (ml []interface{}, err error) {
	o := orm.NewOrm()
	qs := o.QueryTable(new(Pay))
	// query k=v
	for k, v := range query {
		// rewrite dot-notation to Object__Attribute
		k = strings.Replace(k, ".", "__", -1)
		if strings.Contains(k, "isnull") {
			qs = qs.Filter(k, (v == "true" || v == "1"))
		} else {
			qs = qs.Filter(k, v)
		}
	}
	// order by:
	var sortFields []string
	if len(sortby) != 0 {
		if len(sortby) == len(order) {
			// 1) for each sort field, there is an associated order
			for i, v := range sortby {
				orderby := ""
				if order[i] == "desc" {
					orderby = "-" + v
				} else if order[i] == "asc" {
					orderby = v
				} else {
					return nil, errors.New("Error: Invalid order. Must be either [asc|desc]")
				}
				sortFields = append(sortFields, orderby)
			}
			qs = qs.OrderBy(sortFields...)
		} else if len(sortby) != len(order) && len(order) == 1 {
			// 2) there is exactly one order, all the sorted fields will be sorted by this order
			for _, v := range sortby {
				orderby := ""
				if order[0] == "desc" {
					orderby = "-" + v
				} else if order[0] == "asc" {
					orderby = v
				} else {
					return nil, errors.New("Error: Invalid order. Must be either [asc|desc]")
				}
				sortFields = append(sortFields, orderby)
			}
		} else if len(sortby) != len(order) && len(order) != 1 {
			return nil, errors.New("Error: 'sortby', 'order' sizes mismatch or 'order' size is not 1")
		}
	} else {
		if len(order) != 0 {
			return nil, errors.New("Error: unused 'order' fields")
		}
	}

	var l []Pay
	qs = qs.OrderBy(sortFields...)
	if _, err = qs.Limit(limit, offset).All(&l, fields...); err == nil {
		if len(fields) == 0 {
			for _, v := range l {
				ml = append(ml, v)
			}
		} else {
			// trim unused fields
			for _, v := range l {
				m := make(map[string]interface{})
				val := reflect.ValueOf(v)
				for _, fname := range fields {
					m[fname] = val.FieldByName(fname).Interface()
				}
				ml = append(ml, m)
			}
		}
		return ml, nil
	}
	return nil, err
}

// UpdatePay updates Pay by Id and returns error if
// the record to be updated doesn't exist
func UpdatePayById(m *Pay) (err error) {
	o := orm.NewOrm()
	v := Pay{Id: m.Id}
	// ascertain id exists in the database
	if err = o.Read(&v); err == nil {
		var num int64
		if num, err = o.Update(m); err == nil {
			fmt.Println("Number of records updated in database:", num)
		}
	}
	return
}

// DeletePay deletes Pay by Id and returns error if
// the record to be deleted doesn't exist
func DeletePay(id string) (err error) {
	o := orm.NewOrm()
	v := Pay{Id: id}
	// ascertain id exists in the database
	if err = o.Read(&v); err == nil {
		var num int64
		if num, err = o.Delete(&Pay{Id: id}); err == nil {
			fmt.Println("Number of records deleted in database:", num)
		}
	}
	return
}

func GetPayByOrderId(id string) (v []Pay, err error) {
	o := orm.NewOrm()
	qs := o.QueryTable(new(Pay)).Filter("BuyId", id).Limit(-1).OrderBy("Seq")
	_, err = qs.All(&v)
	return
}

func AddPayByRecive(v []*PayItem, orderId, user string) error {
	receivs := make([]*Pay, 0)
	for _, value := range v {
		r := new(Pay)
		r.Id = encrypt.GetGuid()
		r.BuyId = orderId
		r.Seq = value.Seq
		r.Money = value.Money
		r.Date = value.Date
		r.Remark = value.Remark
		r.Creater = user
		r.Ctime = time.Now()
		r.Updater = user
		r.Utime = time.Now()
		r.Status = 0
		r.Isdelete = 0
		receivs = append(receivs, r)
	}
	o := orm.NewOrm()
	_, err := o.InsertMulti(len(receivs), receivs)
	return err
}

func StartPay(buyId string) error {
	o := orm.NewOrm()
	_, err := o.QueryTable(new(Pay)).Filter("BuyId", buyId).Update(orm.Params{
		"Status": 1,
	})
	return err
}


// GroupByBuyId...
// 根据订单Id分组查询
// 返回订单名称，订单id，应付款项
func GroupByBuyId() ([]orm.Params, error) {
	o := orm.NewOrm()
	var l []orm.Params
	sql := `
SELECT name,buy_id, count(*) 
FROM yjk_pay t1 INNER JOIN yjk_buy t2
ON t1.buy_id = t2.id
GROUP BY t2.name, t1.buy_id, t1.status
HAVING
t1.status > 0

`
	qs := o.Raw(sql)
	_, err := qs.Values(&l)
	return l, err
}

func GetPayItemByBusyId(buyId string) ([]orm.Params, error){
	o := orm.NewOrm()
	var l []orm.Params
	qs := o.QueryTable(new(Pay)).Filter("Isdelete", 0).OrderBy("Seq").Filter("BuyId", buyId)
	_, err := qs.Values(&l)
	return l, err
}

func ReceivItemById(id string) error {
	o := orm.NewOrm()
	_, err := o.QueryTable(new(Receiv)).Filter("Id", id).Update(orm.Params{
		"Status": 2,
	})
	return err
}
